package com.example.test_event_and_callback;

import com.example.test_event_and_callback.impl.TestAsyncDto;
import lombok.SneakyThrows;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.context.annotation.Bean;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;

public class Test {

    @SneakyThrows
    public static void main(String[] args) {
        TestAsyncDto dto = new TestAsyncDto();
        String name = "miaowing";
        Method method ;

        try {
            method = TestAsyncDto.class.getMethod("setName", String.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        for (int j = 0; j < 10; j++) {

            long start = System.currentTimeMillis();
            for (int i = 0; i < 10000000; i++) {
                dto.setName(name);
            }
            System.out.println("直接调用:" + (System.currentTimeMillis() - start));

            start = System.currentTimeMillis();
            for (int i = 0; i < 10000000; i++) {
                method.invoke(dto,name);
            }
            System.out.println("反射:" + (System.currentTimeMillis() - start));

            MethodHandle methodHandle = MethodHandles.lookup().unreflect(method).bindTo(dto);
            start = System.currentTimeMillis();
            for (int i = 0; i < 10000000; i++) {
                methodHandle.invokeExact(name);
            }
            System.out.println("固定绑定句柄:" + (System.currentTimeMillis() - start));

            MethodHandle methodHandle1 = MethodHandles.lookup().unreflect(method);
            start = System.currentTimeMillis();
            for (int i = 0; i < 10000000; i++) {
                methodHandle1.bindTo(dto).invokeExact(name);
            }
            System.out.println("手动动态绑定句柄:" + (System.currentTimeMillis() - start));

            MethodHandles.Lookup lookup = MethodHandles.lookup();
            MethodType methodType = MethodType.methodType(void.class,String.class);
            start = System.currentTimeMillis();
            MethodHandle lookup4 = lookup.findVirtual(TestAsyncDto.class, "setName", methodType);
            for (int i = 0; i < 10000000; i++) {
                lookup4.invokeExact(dto,name);
            }
            System.out.println("自动绑定句柄:" + (System.currentTimeMillis() - start));

            BeanWrapper beanWrapper = new BeanWrapperImpl(dto);
            for (int i = 0; i < 10000000; i++) {
                beanWrapper.setPropertyValue("name",name);
            }
            System.out.println("beanWrapper:" + (System.currentTimeMillis() - start));

        }




    }
}
